# 导入库
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score

class ClusterUtils(object):
    """
    聚类工具类
    """
    def __init__(self):
        self.df = pd.read_csv('tourist_agency_visitors.csv')

    def get_k(self):
        """
        获取最佳聚类数
        """
        # 提取特征并标准化
        features = self.df[['out_province_ratio', 'elderly_ratio', 'non_weekend_visitors']]
        scaler = StandardScaler()
        scaled_features = scaler.fit_transform(features)
        scorse = []
        for k in range(2, 10):
            kmeans = KMeans(n_clusters=k, random_state=42)
            labels = kmeans.fit_predict(scaled_features)
            scorse.append(silhouette_score(scaled_features, labels))
        plt.plot(range(2, 10), scorse)
        plt.show()

if __name__ == '__main__':
    cl = ClusterUtils()
    cl.get_k()
